<html>
  <head>
    <!--CSS file (default YUI Sam Skin) -->
    <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.2/build/menu/assets/skins/sam/menu.css">
    <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.2/build/container/assets/skins/sam/container.css" />
    <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.2/build/calendar/assets/skins/sam/calendar.css">

    <link rel="stylesheet" type="text/css" href="/static/stylesheets/datatable.css">
    <link rel="stylesheet" type="text/css" href="/static/stylesheets/main.css" />

    {{title}}
  </head>
  <body class="yui-skin-sam">
  {{header}}

  <b>Next Actions:</b><br />
  <div id="markup" class="grid">
      <table id="actions">
          <thead>
              <tr>
                  <th>Action</th>
                  <th>Category</th>
                  <th>Extra Info</th>
                  <th>Tag</th>
                  <th>Due Date</th>
              </tr>
          </thead>
          <tbody>
          </tbody>
      </table>
  </div>
  <span class="hint">To edit a row, right click on it and choose "Edit"</span>

  <br />
  <br />
  <a name="submitform" />
  <b>Create and Edit:</b>
  <table>
  <tr>
    <td>Action</td>
    <td>
      <input id="action" type="text" name="action" size="50" tabindex="1">
      <a id="cancel_edit" class="hint" href="javascript:cancelEdit()"></a>
    </td>
  </tr>
  <tr>
    <td>Category</td>
    <td>
      <SELECT NAME="category" id="category" tabindex="2">
        <OPTION VALUE="choose">Choose a Category...

        {% for cat in categories %}
          <OPTION VALUE="{{cat.name}}">{{cat.name}}
        {% endfor %}
      </SELECT>
      <a href="/categorypage" class="hint">Add/Edit Categories</a>
    </td>
  </tr>
  <tr>
    <td>Phone</td>
    <td><input id="phone" type="text" name="phone" tabindex="3"></td>
  </tr>
  <tr>
    <td>URL</td>
    <td><input id="url" type="text" name="url" size="50" tabindex="4"></td>
  </tr>
  <tr>
    <td>Tag</td>
    <td><input id="tag" type="text" name="tag" size="50" tabindex="5"></td>
  </tr>
  <tr>
    <td>Due Date?</td>
    <td>
      <input id="due_date_yes" type="radio" name="has_due_date" value="yes">Yes
      <input id="due_date_no" type="radio" name="has_due_date" value="no" tabindex="6" checked>No
    </td>
  </tr>
  <tr>
    <td valign="top">
      <input id="submit_button" type="submit" value="Add" onclick="doAddEdit()" tabindex="7">
    </td>
    <td><div id="due_date_cal" class="grid"></div></td>
  </tr>
  <tr>
    <td colspan="2"><div class="error" id="errorContainer"></div></td>
  </tr>
  </table>
  <input id="due_date" type="hidden" name="due_date" value="">
  <input id="edit_row_id" type="hidden" name="edit_row_id" value="">
  <input id="action_key" type="hidden" name="action_key" value="">

  <br />
  <a name="more" />
  <b>More:</b>
  <ul>
  <li>View <a href="/completed">completed actions</a></li>
  <li>View <a href="/opentasks">all open tasks</a></li>
  <li>Send <a href="javascript:emailReport()">a next action email report</a> to myself <span id="email_result" class="hint"></span></li>
  <li>Send <a href="/sendemail">a category-specific next action email report</a></li>
  </ul>

  {{footer}}

  <!-- YUI COMMON -->
  <!-- Dependencies -->
  <script type="text/javascript" src="http://yui.yahooapis.com/2.5.2/build/yahoo-dom-event/yahoo-dom-event.js"></script>
  <!-- END YUI COMMON -->

  <!-- YUI CALENDAR -->
  <!-- Source file -->
  <script type="text/javascript" src="http://yui.yahooapis.com/2.5.2/build/calendar/calendar-min.js"></script>
  <script>
    var selectedDueDate;

    YAHOO.namespace("example.calendar");

    function dateToLocaleString(dt, cal) {
      var wStr = cal.cfg.getProperty("WEEKDAYS_LONG")[dt.getDay()];
      var dStr = dt.getDate();
      var mStr = cal.cfg.getProperty("MONTHS_LONG")[dt.getMonth()];
      var yStr = dt.getFullYear();
      return (wStr + ", " + dStr + " " + mStr + " " + yStr);
    };

    function mySelectHandler(type,args,obj) {
      var selected = args[0];
      var selDate = this.toDate(selected[0]);

      selectedDueDate = dateToLocaleString(selDate, this);
      document.create_form.due_date.value = selectedDueDate;
    };

    YAHOO.example.calendar.cal1 = new YAHOO.widget.Calendar("cal1","due_date_cal", { title:"Choose a due date:", close:false });
    YAHOO.example.calendar.cal1.selectEvent.subscribe(mySelectHandler, YAHOO.example.calendar.cal1, true);
    YAHOO.example.calendar.cal1.render();

    // Listener to show the Calendar when "Yes" is clicked
    YAHOO.util.Event.addListener("due_date_yes", "click", YAHOO.example.calendar.cal1.show, YAHOO.example.calendar.cal1, true);

    // Listener to hide the Calendar when "No" is clicked
    YAHOO.util.Event.addListener("due_date_no", "click", YAHOO.example.calendar.cal1.hide, YAHOO.example.calendar.cal1, true);

    function updateCal(month, day, year) {
      if (!isNaN(month) && !isNaN(day) && !isNaN(year)) {
        var date = month + "/" + day + "/" + year;

        YAHOO.example.calendar.cal1.select(date);
        YAHOO.example.calendar.cal1.cfg.setProperty("pagedate", month + "/" + year);
        YAHOO.example.calendar.cal1.render();
      }
    }
  </script>
  <!-- END YUI CALENDAR -->

  <!-- YUI MENU -->
  <!-- Dependencies -->
  <script type="text/javascript" src="http://yui.yahooapis.com/2.5.2/build/container/container_core-min.js"></script>

  <!-- Source File -->
  <script type="text/javascript" src="http://yui.yahooapis.com/2.5.2/build/menu/menu-min.js"></script>
  <!-- END YUI MENU -->

  <!-- YUI DATATABLE -->
  <!-- Dependencies -->
  <script type="text/javascript" src="http://yui.yahooapis.com/2.5.2/build/element/element-beta-min.js"></script>
  <script type="text/javascript" src="http://yui.yahooapis.com/2.5.2/build/datasource/datasource-beta-min.js"></script>

  <!-- Source files -->
  <script type="text/javascript" src="http://yui.yahooapis.com/2.5.2/build/datatable/datatable-beta-min.js"></script>
  <script>
  var actionTable;
  var currentSortKey = "due";
  var currentSortDir = YAHOO.widget.DataTable.CLASS_ASC;

  formatDueDate = function(elCell, oRecord, oColumn, oData) {
    if (oData == "Invalid Date" || oData == "NaN") {
      elCell.innerHTML = "";
    }
    else {
      YAHOO.widget.DataTable.formatDate(elCell, oRecord, oColumn, oData);
    }
  };

  formatMarkComplete = function(elCell, oRecord, oColumn, oData) {
	  var key = getTaskKey(oRecord.getData("action"));
    var row = elCell.parentNode;
    elCell.align = 'center';
	  elCell.innerHTML = '<a href="javascript:markActionComplete(\'' + key + '\', \'' + row.id + '\')"><img src="/static/images/Check_mark_23x20.png"></a>';
  };

  formatDelete = function(elCell, oRecord, oColumn, oData) {
	  var key = getTaskKey(oRecord.getData("action"));
    var row = elCell.parentNode;
    elCell.align = 'center';
	  elCell.innerHTML = '<a href="javascript:doDelete(\'' + key + '\', \'' + row.id + '\')"><img src="/static/images/X_mark_18x18.png"></a>';
  };

  YAHOO.util.Event.addListener(window, "load", function() {
      YAHOO.example.EnhanceFromMarkup = new function() {
          var myColumnDefs = [
              {key:"action", label:"Action", sortable:true, formatter:formatTaskAction},
              {key:"category", label:"Category", sortable:true},
              {key:"extra", label:"Extra Info", sortable:true},
              {key:"tag", label:"Tag", sortable:true},
              {key:"due", label:"Due Date", formatter:formatDueDate, sortable:true},
              {key:"complete", label:"Complete", formatter:formatMarkComplete},
              {key:"delete", label:"Delete", formatter:formatDelete}
          ];

          this.myDataSource = new YAHOO.util.DataSource(YAHOO.util.Dom.get("actions"));
          this.myDataSource.responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE;
          this.myDataSource.responseSchema = {
              fields: [
                      {key:"action"},
                      {key:"category"},
                      {key:"extra"},
                      {key:"tag"},
                      {key:"due", parser:YAHOO.util.DataSource.parseDate}
              ]
          };

          this.myDataTable = new YAHOO.widget.DataTable("markup", myColumnDefs, this.myDataSource,
                  { sortedBy:{key:"due",dir:"asc"} }
          );
          actionTable = this.myDataTable;

          this.onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
              var task = p_aArgs[1];
              if(task) {
                  // Extract which TR element triggered the context menu
                  var elRow = this.contextEventTarget;
                  elRow = p_myDataTable.getTrEl(elRow);
                  var oRecord = p_myDataTable.getRecord(elRow);
                  var key = getTaskKey(oRecord.getData("action"));

                  if(elRow) {
                      switch(task.index) {
                          case 0:
                              doGetAction(key);
                              $("edit_row_id").value = elRow.id;
                              $("action_key").value = key;
                              $("submit_button").value = "Update";
                              $("cancel_edit").innerHTML = "Cancel edit";
                              
                          case 1:
                              doConvertToSomedayMaybe(key);
                      }
                  }
              }
          };
          this.myContextMenu = new YAHOO.widget.ContextMenu("mycontextmenu", {trigger:this.myDataTable.getTbodyEl()});
          this.myContextMenu.addItem("Edit");
          this.myContextMenu.addItem("Move to Someday/Maybe List");
          this.myContextMenu.render("markup");
          this.myContextMenu.clickEvent.subscribe(this.onContextMenuClick, this.myDataTable);

          this.myDataTable.subscribe("columnSortEvent", function(oArgs) {
              currentSortKey = oArgs.column.key;
              currentSortDir = oArgs.dir;
          });
          doGetAllActions();
      };
  });
  </script>
  <!-- END YUI DATATABLE -->

  <!-- RPC -->
  <script type="text/javascript" src="./static/javascript/json2.js"></script>
  <script type="text/javascript" src="./static/javascript/gtd_rpc.js"></script>
  <script type="text/javascript" src="./static/javascript/gtd_utils.js"></script>
  <script type="text/javascript">
  var emailMsgTimeout;
  function emailReport() {
    clearTimeout(emailMsgTimeout);
    $('email_result').innerHTML = 'Attempting to send email report...';
    server.EmailNextActions(onEmailReportSuccess);
  }
  
  function onEmailReportSuccess(response) {
    if (isError(response)) {
      $('email_result').innerHTML = errorString(response);
    }
    else {
      $('email_result').innerHTML = response;
    }
    emailMsgTimeout = setTimeout('$("email_result").innerHTML = ""', 5000);
  }
  
  function markActionComplete(key, rowId) {
    server.MarkTaskComplete(key, rowId, onDeleteSuccess);
  }

  function clearForm() {
    $('action').value = '';
    $('category').selectedIndex = 0;
    $('phone').value = '';
    $('url').value = '';
    $('tag').value = '';
    $('due_date_yes').checked = false;
    $('due_date_no').checked = true;
    YAHOO.example.calendar.cal1.hide();
  }

  function cancelEdit() {
    clearForm();
    clearEditFields();
  }

  function clearEditFields() {
    $('edit_row_id').value = '';
    $('action_key').value = '';
    $('submit_button').value = 'Add';
    $('cancel_edit').innerHTML = '';
  }

  function doDelete(action, rowId) {
    server.DeleteTask(action, rowId, onDeleteSuccess);
  }

  function onDeleteSuccess(response) {
    actionTable.deleteRow(response);
  }

  function doAddEdit() {
    try {
      server.AddEditAction(
        $('action').value,
        $('category').value,
        $('phone').value,
        $('url').value,
        $('tag').value,
        $('due_date_yes').checked,
        selectedDueDate,
        $('edit_row_id').value,
        $('action_key').value,
        onAddEditReturn);
      clearEditFields();
    }
    catch (err) {
      alert(err);
    }
  }

  function onAddEditReturn(response) {
    try {
      if (isError(response)) {
        $('errorContainer').innerHTML = errorString(response);
      }
      else {
        $('errorContainer').innerHTML = '';
        var record = YAHOO.widget.DataTable._cloneObject(response);

        // Figure out if this is an update or an add
        if (response['edit_row_id'] == '') {
          actionTable.addRow(record);
        }
        else {
          actionTable.updateRow(response['edit_row_id'], record);
        }
        var column = actionTable.getColumn(currentSortKey);
        actionTable.sortColumn(column, currentSortDir);
        clearForm();
      }
    }
    catch (err) {
      alert(err);
    }
  }

  function doGetAllActions() {
    server.GetActions(onGetAllReturn);
  }

  function onGetAllReturn(response) {
	  for (i in response) {
  		var record = YAHOO.widget.DataTable._cloneObject(response[i]);
  		actionTable.addRow(record);
	  }
  }

  function doGetAction(key) {
    server.GetAction(key, onGetReturn);
  }

  function onGetReturn(response) {
    location.href = "#submitform";
    $('action').value = getTaskAction(response['action']);
    $('category').value = response['category'];
    $('phone').value = response['phone'];
    $('url').value = response['url'];
    $('tag').value = response['tag'];
    var has_due = (response['due'] != '');
    $('due_date_yes').checked = has_due;
    $('due_date_no').checked = !has_due;
    if (has_due) {
      YAHOO.example.calendar.cal1.show();
      updateCal(response['due_month'], response['due_day'], response['due_year']);
    }
    else {
      YAHOO.example.calendar.cal1.hide();
    }
  }
  
  function doConvertToSomedayMaybe(key) {
    alert(key);
  }
  </script>
  <!-- END RPC -->
  </body>
</html>
